/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gamaze;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JPanel;

/**
 *
 * @author pborrego
 */
public class MazeViewer extends JPanel {
    public MazeViewer() {
        super();

        this.cellSize = 5;
        this.wallSize = 1;

        this.setupComponents();

        this.renderMaze(10,10);
    }

    private void setupComponents() {


        // set up viewport...
        this.viewport = new JPanel();
        this.setSize(this.getWidth(), this.getHeight());

        this.viewport.setSize(this.getWidth(), this.getHeight());

        this.add(this.viewport);
        
        this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                MazeViewer mv = (MazeViewer)e.getComponent();
                mv.setViewportSize(mv.getSize());
            }
        });
    }

    public final void renderMaze(int w, int h) {
        this.viewport.removeAll();
        MazeGen generator = new MazeGen(w, h);
        generator.dfsMaze();

        this.mz = new Maze(w, h, 0, (w*h)-1, generator.getMaze());
        this.cells = new CellRenderer[this.mz.getWidth() * this.mz.getHeight()];
        int[] rmap = mz.getRestrictionMap();

        this.viewport.setLayout(new GridLayout(this.mz.getHeight(), this.mz.getWidth()));

        // set up grid...
        for(int i=0; i<cells.length; i++) {
            cells[i] = new CellRenderer(this.cellSize, this.wallSize);

            if( w > i ) {
                cells[i].setCellType(CellRenderer.BORDER_TOP);
            }

            if( 0 == (i % w) ) {
                cells[i].setCellType(CellRenderer.BORDER_LEFT);
            }

            cells[i].setRestrictionCode(rmap[i]);
            this.viewport.add(cells[i]);
        }


        this.cells[this.mz.getStart()].setCellType(CellRenderer.START);
        this.cells[this.mz.getEnd()].setCellType(CellRenderer.END);

        this.viewport.revalidate();
    }

    public void setViewportSize(Dimension d) {
        this.viewport.setSize(d);
//        this.viewport.revalidate();
    }

    private Maze mz;
    private int cellSize;
    private int wallSize;
    private CellRenderer cells[];
    private JPanel viewport;
}
